<template>
    <div>
        <el-input v-bind="$attrs" v-on="$listeners" v-model="getMapValue">
            <template slot="append">
                <el-button type="primary" @click="getOptionsList('28.212292','112.98934')">获得定位信息</el-button>
            </template>
        </el-input>
        <el-dialog title="腾讯地图" :visible.sync="TxMapVisible" width="60%" :before-close="function(){return TxMapVisible = false}">
            <div style="margin: 15px 0px;">
                <el-autocomplete
                v-model="mapSearch"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入地址内容"
                @select="handleSelect"
                style="width:100%;"
                >
                </el-autocomplete>
           </div>
            <div id="container" style="width:100%; height:400px"></div>
        </el-dialog>
    </div>
</template>

<script>
import Md5 from 'crypto-js/md5.js';
import { getParent} from '../utils'
export default {
    data(){
        return {
            mapValue:'',
            TxMapVisible:false,
            mapSearch:'',
            txKey:'63PBZ-NJTCU-AXPVJ-2UXI2-BE6L2-HKB4J',
            signKey:'XQ4B8z9i4P1Ve7J5ybnmS6yEbvq7o6L',
        }
    },
    props: {
      value: {
        type: String,
        defalut:()=>{
            return '';
        }
      }
    },
    computed: {
        parent() {
            return getParent.call(this)
        },
        getMapValue:{
          get(){
            return this.value;
          },
          set(val){
              this.mapValue = val;
          }

        }
    },
    methods: {
        getSign(data,key,url){
            var arr = this.sortList(data);
            var str = this.splicingSingParam(arr);
            console.log(url + '?' +str + key);
             return Md5( url + '?' +str + key).toString();
         },
         //字典排序
        sortList (Arr) {
            var obj = JSON.parse(JSON.stringify(Arr));

            var indexArr = [];
            for (var i in obj) {
                indexArr.push(i);
            }


            indexArr.sort();
            var newArr = {};
            for (var j in indexArr) {
                for (var i in obj) {
                if (indexArr[j] == i) {
                    newArr[indexArr[j]] = obj[indexArr[j]];
                }
                }
            }
            return newArr;
        },
        splicingSingParam(arr){
            var str = '';
            for(var i in arr) {
                str += i + '=' + arr[i] + '&';
            }

            return str.substring(0,str.length-1);
        },
        querySearchAsync(val,cb){
            var that = this;
            let url = "https://apis.map.qq.com/ws/place/v1/suggestion"
            let keyword = val
            var param =  {
                key: this.txKey,
                boundary: "region(全国)",
                keyword: keyword,
                output: "jsonp"
            };

            //签名验证没通过  有时间再弄

            // url += '?sig=' + this.getSign( param , this.signKey ,'/ws/place/v1/suggestion');

            // param.boundary = "region(全国)";
            // param.output = "jsonp";
            // console.log(param,url);
            this.$jsonp(url,param).then(res => {
                console.log(res,res.data)
                if(res.status == 0) {
                    var arr = [];
                    res.data.forEach(element => {
                        element.value = element.title;
                        arr.push(element);
                    });

                    cb(arr);
                }
            }).catch(err => {
                console.log(err)
            })
        },
        handleSelect(item) {
           
            this.getOptionsList(item.location.lat,item.location.lng);
            this.TxMapVisible = false;
            this.mapValue = item.address + item.title;
            let model = this.parent.currentModel;
            if(model) {
                model.province = item.province;
                model.city = item.city;
                model.area = item.district;
                model.lat = item.location.lat;
                model.lng = item.location.lng;
            }
             console.log('item',model);
            this.$emit('input',this.mapValue);
        },
        getOptionsList(lat='28.212292',lng='112.98934'){

            var that = this;
            this.TxMapVisible = true;
            var key = that.txKey;
            let url = 'https://map.qq.com/api/js?v=2.exp&key='+key+'&callback=init';
            this.loadJS(url,function(){
                 window.init = function() {
                    var center = new qq.maps.LatLng(lat, lng);
                    var map = new qq.maps.Map(document.getElementById('container'),{
                            center: center,
                            zoom: 13,
                            draggable: false,
                            scrollwheel: false,
                            disableDoubleClickZoom: false
                        });

                    var marker = new qq.maps.Marker({
                        position: center,
                        map: map,
                    });
                 }
            })
        },
        loadJS:function( url, callback ){

            var script = document.createElement('script'),

                fn = callback || function(){};

            script.type = 'text/javascript';



            //IE

            if(script.readyState){

                script.onreadystatechange = function(){

                    if( script.readyState == 'loaded' || script.readyState == 'complete' ){

                        script.onreadystatechange = null;

                        fn();

                    }

                };

            }else{

                //其他浏览器

                script.onload = function(){

                    fn();

                };

            }

            script.src = url;

            document.body.appendChild(script);

        },
    }
}
</script>
